<template>
  <div class="permission">
    <el-card>
      <div style="text-align: right">
        <el-button type="primary" @click="addEvent(1, '0')">添加菜单</el-button>
      </div>
      <!-- table中展示树形数据
        1.需要数据中有children字段(转化过)
        2.在table上设置唯一标识row-key字段的值
        3.显示数据内容 prop绑定数据字段
         -->
      <el-table :data="list" row-key="id">
        <el-table-column label="菜单名称" prop="name" />
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <div>
              <span v-if="row.type === 1" style="padding-right: 15px">
                <el-button
                  type="text"
                  @click="addEvent(1, row.id)"
                >添加页面</el-button>
                <el-button
                  type="text"
                  @click="addEvent(2, row.id)"
                >添加按钮</el-button>
              </span>
              <el-button
                type="text"
                @click="editEvent(row)"
              >编辑权限点</el-button>
              <el-button type="text" @click="delEvent(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加的对话框 -->
    <Add ref="add" @getData="getData" />
  </div>
</template>

<script>
import { sysPermission, sysPermissionDel } from '@/api/permission.js'
import Add from './components/add.vue'
export default {
  name: '',
  components: {
    Add
  },
  data() {
    return {
      list: []
    }
  },
  computed: {},
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysPermission()
      console.log(res, '权限')
      this.list = this.changeData(res.data, '0')
    },
    // 处理树形结构数据 utils中有封装函数 可以直接使用
    changeData(arr, str) {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },
    // 点击添加 通过ref获取子组件实例对象 修改子组件的属性
    addEvent(type, pid) {
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'add'
      this.$refs.add.form.type = type
      this.$refs.add.form.pid = pid
    },
    // 点击编辑权限点
    editEvent(row) {
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'edit'
      console.log(row, '当前行数据')
      // 深拷贝给到子组件的form表单 进行数据的回显
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    },
    // 点击删除
    delEvent(id) {
      // 提示
      this.$confirm('确定删除吗?', '提示')
        .then(async() => {
          // 确定后 调用接口
          await sysPermissionDel(id)
          // 渲染页面
          this.getData()
          // 提示删除成功
          this.$message.success('删除成功')
        })
        .catch(() => {})
    }
  }
}
</script>
<style lang="scss" scoped>
.permission {
  padding: 20px;
}
</style>
